package com.marktotop.exception;

import com.marktotop.response.ResultBean;
import com.marktotop.response.ResultCode;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * GlobalExceptionHandler 全局异常处理类
 *
 * @author WXLD
 * @Data 2021/6/18
 * @Since 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResultBean ExceptionHandler(Exception e){
        if (e instanceof GlobalException){
            // Exception 处理
            GlobalException ex = (GlobalException) e;
            return ResultBean.result(ex.getResultCode());
        } else if (e instanceof BindException){
            // BindException 处理
            BindException ex = (BindException) e;
            ResultBean result = ResultBean.result(ResultCode.FILE_DATA_ERROR);
            result.setMessage("参数校验异常："+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        return ResultBean.error();
    }
}
